package com.guit.hrms.config;

import com.guit.hrms.manager.DynamicTaskManager;
import com.guit.hrms.po.interview.Offer;
import com.guit.hrms.po.utilsPO.PageBean;
import com.guit.hrms.service.IntervieweeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class DynamicTaskConfig {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IntervieweeService intervieweeService;

    @Autowired
    private DynamicTaskManager taskManager;

    /**
     * 应用启动完成后初始化所有未过期的offer任务
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initializeTasks() {
        LocalDateTime now = LocalDateTime.now();
        log.info("开始初始化 Offer 过期检查任务... 当前时间: {}", now.format(DATE_FORMATTER));

        int pageSize = 100;
        int page = 1;
        int totalTasks = 0;
        int failedTasks = 0;
        int skippedTasks = 0;

        try {
            boolean hasMore;
            do {
                PageBean offerPage = intervieweeService.findAllActiveOffers(page, pageSize);
                List<Offer> offers = offerPage.getRow();

                if (offers.isEmpty() && page == 1) {
                    log.info("没有找到需要处理的 Offer 记录");
                    return;
                }

                for (Offer offer : offers) {
                    try {
                        if (offer.getExpiryTime().isBefore(now)) {
                            log.debug("跳过已过期的 Offer，ID: {}，过期时间: {}",
                                    offer.getId(), offer.getExpiryTime().format(DATE_FORMATTER));
                            skippedTasks++;
                            continue;
                        }

                        taskManager.addTask(
                            offer.getId(),
                            offer,
                            () -> intervieweeService.checkOfferExpiry(offer.getId())
                        );
                        log.debug("成功添加 Offer 任务，ID: {}，过期时间: {}",
                                offer.getId(), offer.getExpiryTime().format(DATE_FORMATTER));
                        totalTasks++;
                    } catch (Exception e) {
                        log.error("Offer 任务初始化失败，ID: {}，原因: {}", offer.getId(), e.getMessage());
                        failedTasks++;
                    }
                }

                hasMore = offerPage.getTotal() > (long) page * pageSize;
                page++;
            } while (hasMore);

            log.info("Offer 任务初始化完成。总任务数: {}，失败: {}，已过期跳过: {}",
                    totalTasks, failedTasks, skippedTasks);

        } catch (Exception e) {
            log.error("Offer 任务初始化过程发生错误", e);
        }
    }

    /**
     * 定期检查任务状态，清理已完成或失效的任务
     */
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    public void cleanupTasks() {
        LocalDateTime now = LocalDateTime.now();
        log.info("开始清理过期任务... 当前时间: {}", now.format(DATE_FORMATTER));

        try {
            int initialCount = taskManager.getActiveTaskCount();

            // 获取所有活跃的offer
            PageBean offerPage = intervieweeService.findAllActiveOffers(1, Integer.MAX_VALUE);
            List<Offer> activeOffers = offerPage.getRow();

            // 检查每个任务是否仍然有效
            taskManager.cleanupInvalidTasks(activeOffers);

            int finalCount = taskManager.getActiveTaskCount();
            int removedCount = initialCount - finalCount;

            if (removedCount > 0) {
                log.info("任务清理完成。清理前: {}，清理后: {}，共清理: {} 个无效任务",
                        initialCount, finalCount, removedCount);
            } else {
                log.info("任务清理完成。当前活跃任务数: {}，没有需要清理的任务", finalCount);
            }
        } catch (Exception e) {
            log.error("任务清理过程发生错误", e);
        }
    }
}
